import React, { Fragment, useEffect, useState } from "react";
import "./Search.scss";
import NavBar from "@/components/NavBar/NavBar";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Button, Input, Modal } from "antd-mobile";
import SvgIcon from "@/components/SvgIcon/SvgIcon";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { clearSearchList, pushSearchList } from "@/store/modules/searchStore";
import store from "@/store";

const Search = () => {
   const navigate = useNavigate();

   const enhanceDispatch = useEnhanceDispatch();


   // 搜索的关键字列表
   const searchList: string[] = useEnhanceSelector(state => state.searchStore.searchList);

   // 搜索关键字
   const [goodsName, setGoodsName] = useState<string>("");

   /**
    * @description 点击搜索按钮的回调函数
    * */
   const handleSearch = () => {
      enhanceDispatch(pushSearchList(goodsName));
      navigate(`/good-list?goodsName=${goodsName}`);
      setGoodsName("");
   };

   /**
    * @description 点击删除的回调函数
    * */
   const handleClear = async () => {
      const result: boolean = await Modal.confirm({ content: "确认删除搜索历史吗?" });
      if (!result) return;
      enhanceDispatch(clearSearchList());
   };

   const renderSearchResult = () => {
      if (searchList.length) {
         return (
            <Fragment>
               <div className="header">
                  <span>最近搜索</span>
                  <span onClick={handleClear}>
                  <SvgIcon name="delete" width="20px" height="20px"></SvgIcon>
               </span>
               </div>
               <div className="history">
                  {searchList.map(item => <div className="history-item" key={item} onClick={() => navigate(`/good-list?goodsName=${item}`)}>{item}</div>)}
               </div>
            </Fragment>
         );
      } else {
         return (
            <div className="empty">
               <SvgIcon name="search-empty" width="200px" height="200px"></SvgIcon>
               <span>请搜索需要的商品</span>
            </div>
         );
      }
   };

   useEffect(() => {
      store.subscribe(() => {
         localStorage.setItem("list", JSON.stringify(store.getState().searchStore.searchList));
      });
   }, []);

   return (
      <div className="search-container">
         {/*导航栏*/}
         <NavBar backIcon onBack={() => navigate(-1)} children="商品搜索"></NavBar>
         {/*输入框*/}
         <div className="search-input">
            <SvgIcon name="search" width="15px" height="15px"></SvgIcon>
            <Input placeholder="请输入您搜索的商品" value={goodsName} onChange={(value: string) => setGoodsName(value)}></Input>
            <Button color="primary" onClick={handleSearch}>搜索</Button>
         </div>
         {/*搜索历史*/}
         <div className="search-history">
            {
               renderSearchResult()
            }
         </div>
      </div>
   );
};

export default Search;
